#!/usr/bin/env python
# -*- encoding=utf-8 -*-
'''
Created on 2018/03/29

@author: peulerosci,rwx403335
'''

import logging
import logging.config
import xml.etree.ElementTree as ET
from subprocess import *
import os, re, sys, datetime
reload(sys)
sys.setdefaultencoding('utf8')

if not os.path.isdir("log"):
    os.mkdir("log")
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("copy_jenkins")

GERRIT_BRANCH = os.getenv('GERRIT_BRANCH')
if GERRIT_BRANCH == 'next_net' or GERRIT_BRANCH == 'next_hack' or GERRIT_BRANCH == 'next_kernel' or GERRIT_BRANCH == 'next_docker' or GERRIT_BRANCH == 'next_openeuler' :
    BRANCH = 'next'

REPO_DIR = '/usr1/jenkins/EulerOS_' + BRANCH
PROJECT = os.getenv('GERRIT_PROJECT')


def shell_cmd(s_cmd_line, inmsg=None):
    p = Popen(s_cmd_line, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    if inmsg:
        p.stdin.write(inmsg)
    out, err = p.communicate()
    return p.returncode, out, err


def get_project_path():
    default_xml = REPO_DIR + '/.repo/manifest.xml'
    with open(default_xml, 'r') as myfile:
        mystr = myfile.read()
        tmppath = re.findall('<project path="(.+)"\s+name="{0}"'.format(PROJECT), mystr)
        if len(tmppath) == 1:
            mypath = tmppath[0]
            return mypath
            
        xml_list = re.findall(r'<include name="(.+)"/>', mystr)
        mypath = ''
        for next_xml in xml_list:
            with open(REPO_DIR + '/.repo/manifests/' + next_xml) as myxml:
                tmp_str = myxml.read()
                tmppath = re.findall('<project path="(.+)"\s+name="{0}"'.format(PROJECT), tmp_str)
                if len(tmppath) == 1:
                    mypath = tmppath[0]
                    break
        if mypath == '':
            logger.error('can not find this git project: {0}'.format(PROJECT))
            sys.exit(1)

        return mypath


if __name__ == "__main__":
    project_dir = REPO_DIR + '/' + get_project_path()
    spec = "kernel.spec"
    #step one
    ret, out, err = shell_cmd('cd {0};git diff --name-status HEAD~1 HEAD~0'.format(project_dir))
    if ret != 0:
        print "run: %s : failed,the out is %s,the err is %s" % (COMMOND, out, err)
        sys.exit(1)
    spec_list = re.findall('M\s(.+\.spec)', out)
    print "-------------spec_list---------------"
    for file in spec_list:
        print file
    print "-------------------------------------"
    if len(spec_list) == 0:
        logger.info('No spec changed, so exit as success')
        sys.exit(0)
    else:
        exist_flag = 0
        for file in spec_list:
            if file == 'kernel.spec':
                exist_flag = 1
                break
        if exist_flag == 0:
            logger.info('kernel.spec is not changed, so exit as success')
            sys.exit(0)
    #step two
    ret, out, err = shell_cmd('cd {0}; git rev-parse HEAD'.format(project_dir))
    if ret != 0:
        print "run: %s : failed,the out is %s,the err is %s" % (COMMOND, out, err)
        sys.exit(1)
    first_commitid = out
    ret, out, err = shell_cmd('cd {0}; git checkout {1}'.format(project_dir, first_commitid))
    if ret != 0:
        print "run: %s : failed,the out is %s,the err is %s" % (COMMOND, out, err)
        sys.exit(1)
    exist_flag = 0
    with open(project_dir + '/' + spec) as myfile:
        for line in myfile.readlines():
            if 'define rpmversion' in line:
                rpm_version_new = line.split(' ')[2].replace('\n','').replace('\r','')
                exist_flag = exist_flag + 1
            if 'define pkgrelease' in line:
                pkg_release_new = line.split(' ')[2].replace('\n','').replace('\r','')
                exist_flag = exist_flag + 1
            if exist_flag == 2:
                break
    print "[new] exist_flag  ", exist_flag
    if exist_flag < 2:
        logger.error('[new] Lost some version information in {0}'.format(spec))
        sys.exit(1)

    ret, out, err = shell_cmd('cd {0}; git checkout HEAD~1'.format(project_dir))
    if ret != 0:
        print "run: %s : failed,the out is %s,the err is %s" % (COMMOND, out, err)
        sys.exit(1)

    exist_flag = 0
    with open(project_dir + '/' + spec) as myfile:
        for line in myfile.readlines():
            if 'define rpmversion' in line:
                rpm_version_old = line.split(' ')[2].replace('\n','').replace('\r','')
                exist_flag = exist_flag + 1
            if 'define pkgrelease' in line:
                pkg_release_old = line.split(' ')[2].replace('\n','').replace('\r','')
                exist_flag = exist_flag + 1
            if exist_flag == 2:
                break
    print "[old] exist_flag  ", exist_flag
    if exist_flag < 2:
        logger.error('[old] Lost some version information in {0}'.format(spec))
        sys.exit(1)

    logger.info('rpm_version_new :{0}  rpm_version_old :{1}'.format(rpm_version_new, rpm_version_old))
    logger.info('pkg_release_new :{0}  pkg_release_old :{1}'.format(pkg_release_new, pkg_release_old))

    if rpm_version_new != rpm_version_old or pkg_release_new != pkg_release_old:
        print "The KABI of kernel-4.19 is changed"
        sys.exit(1)
